//
// Created by wormtql on 2020/11/18.
//

#include <map>
#include <string>
#include <cstring>
#include <fstream>
#include <queue>
#include <vector>
#include <sstream>
#include <iostream>
#include <set>
#include <cmath>

using namespace std;

bool parse_trace_line(const char * line, char * version, char * commit_id, vector<string> & trace) {
    int i = 0;
    int state = 0;

    int _v = 0;
    int _c = 0;
    char _trace[100] = { 0 };
    int _t = 0;
    while(line[i]) {
        if (state == 0) {
            if (line[i] == '\t' || line[i] == ' ') {
                version[_v] = 0;
                state = 1;
            } else {
                version[_v++] = line[i];
                i++;
            }
        } else if (state == 1) {
            if (line[i] == '\t' || line[i] == ' ') {
                i++;
            } else {
                state = 2;
            }
        } else if (state == 2) {
            if (line[i] == '\t' || line[i] == ' ') {
                commit_id[_c] = 0;
                state = 3;
            } else {
                commit_id[_c++] = line[i];
                i++;
            }
        } else if (state == 3) {
            if (line[i] == '\t' || line[i] == ' ') {
                i++;
            } else {
                state = 4;
            }
        } else if (state == 4) {
            if (line[i] == '\'') {
                state = 5;
                i++;
            } else if (line[i] == ']') {
                state = 6;
                i++;
            } else {
                i++;
            }
        } else if (state == 5) {
            if (line[i] == '\'') {
                _trace[_t] = 0;
                _t = 0;
                string s(_trace);
                trace.push_back(s);
                state = 4;
                i++;
            } else {
                _trace[_t++] = line[i];
                i++;
            }
        } else if (state == 6) {
            i++;
        }
    }

    return true;
}

int main(int argc, char * argv[]) {
    if (argc < 3) {
        printf("usage: app <calltrace.txt> <trace_out.txt(comma split)>\n");
        return 0;
    }

    ifstream file(argv[1]);
    ofstream out_file(argv[2]);
    char buf[10000];
    while (file.getline(buf, 10000)) {
        char version[100];
        char commit_id[100];
        vector<string> ts;
        parse_trace_line(buf, version, commit_id, ts);

        for (auto i = ts.begin(); i != ts.end(); i++) {
            out_file << *i;
            if (i + 1 != ts.end()) {
                out_file << ",";
            }
        }
        out_file << endl;
    }
    file.close();
    out_file.close();

    return 0;
}